package com.cls.mc_demo.config;

import lombok.extern.slf4j.Slf4j;
import org.tio.client.intf.TioClientListener;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;

/**
 * Tio客户端监听器
 *
 * @author CLS
 * @since 2023/08/04
 */
@Slf4j
public class CustomClientTioMonitor implements TioClientListener {
    private boolean state = false;

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        log.info("isConnected:{},isReconnect:{}", isConnected, isReconnect);
        state = true;
        while (state) {
            System.out.println();
            /*向《D30000》*/
            String write = "50 00 00 FF FF 03 00 12 00 10 00 01 14 00 00 30 75 00 A8 03 00 01 00 00 00 0" + randomNumber() + " 00";
            log.info("写入：{}", write);
            CustomClientConfig.send(write.replaceAll(" ", ""));
            Thread.sleep(100);
            /*读取上面写入的值*/
            String read = "50 00 00 FF FF 03 00 0C 00 10 00 01 04 00 00 30 75 00 A8 03 00";
            log.info("读取：{}", read);
            CustomClientConfig.send(read.replaceAll(" ", ""));
            Thread.sleep(3000);
        }
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {

    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {

    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {

    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {

    }

    //连接中断处理方法
    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        log.info("连接关闭....");
        state = false;
    }

    private int randomNumber() {
        int n = 1, m = 9;
        return m + (int) (Math.random() * (n + 1 - m));
    }
}
